<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="chat-title">
            <el-button icon="ArrowLeft" circle @click="goBack"></el-button>
            <span v-if="currentFriend">{{ currentFriend.nickname || currentFriend.username }}</span>
            <span v-else>消息中心</span>
          </div>
          <div>
            <el-button type="primary" circle icon="Refresh" @click="reloadMessages"></el-button>
          </div>
        </div>
      </template>

      <div class="chat-container">
        <!-- 好友列表 -->
        <div class="friends-sidebar">
          <el-input
            v-model="searchText"
            placeholder="搜索好友..."
            prefix-icon="Search"
            clearable
            class="search-input"
          />

          <div class="friend-list">
            <div
              v-for="friend in filteredFriends"
              :key="friend.id"
              class="friend-item"
              :class="{ active: currentFriendId === friend.id }"
              @click="selectFriend(friend)"
            >
              <div class="friend-avatar">
                <el-avatar :size="40" :src="friend.avatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div :class="['status-dot', friend.status]"></div>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.nickname || friend.username }}</div>
                <div class="last-message">{{ getLastMessage(friend) }}</div>
              </div>
              <div class="friend-meta">
                <div class="message-time">{{ getLastMessageTime(friend) }}</div>
                <el-badge
                  v-if="friend.unreadCount > 0"
                  :value="friend.unreadCount"
                  class="unread-badge"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天内容区 -->
        <div class="chat-content">
          <template v-if="currentFriendId">
            <!-- 消息列表 -->
            <div ref="messageListRef" class="message-list">
              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>

              <el-empty v-else-if="messages.length === 0" description="暂无消息记录" />

              <template v-else>
                <div v-for="(message, index) in messages" :key="message.id" class="message-item">
                  <!-- 日期分隔线 -->
                  <div v-if="shouldShowDateDivider(message, index)" class="date-divider">
                    <span>{{ formatDateDivider(message.createdAt) }}</span>
                  </div>

                  <!-- 消息气泡 -->
                  <div
                    class="message-bubble"
                    :class="{
                      'message-sent': message.senderId === userId,
                      'message-received': message.senderId !== userId,
                    }"
                  >
                    <el-avatar
                      v-if="message.senderId !== userId"
                      :size="36"
                      :src="message.senderAvatar"
                      class="sender-avatar"
                    />

                    <div class="message-content">
                      <div
                        class="message-text"
                        :class="{
                          'sent-text': message.senderId === userId,
                          'received-text': message.senderId !== userId,
                          'image-message': message.type === 'image',
                          'file-message': message.type === 'file',
                        }"
                      >
                        <!-- 文本消息 -->
                        <span v-if="message.type === 'text'">{{ message.content }}</span>

                        <!-- 图片消息 -->
                        <div v-else-if="message.type === 'image'">
                          <el-image
                            :src="message.fileUrl"
                            :preview-src-list="[message.fileUrl]"
                            fit="cover"
                            class="message-image"
                          />
                        </div>

                        <!-- 文件消息 -->
                        <div v-else-if="message.type === 'file'" class="file-container">
                          <el-icon><Document /></el-icon>
                          <span class="file-name">{{ message.fileName }}</span>
                          <span class="file-size">{{ formatFileSize(message.fileSize) }}</span>
                          <el-button
                            type="primary"
                            size="small"
                            text
                            @click="downloadFile(message)"
                          >
                            下载
                          </el-button>
                        </div>

                        <!-- 表情消息 -->
                        <div v-else-if="message.type === 'emoji'" class="emoji-container">
                          <span class="emoji">{{ message.content }}</span>
                        </div>
                      </div>

                      <div class="message-time">
                        {{ formatMessageTime(message.createdAt) }}
                        <el-icon
                          v-if="message.senderId === userId"
                          :class="['message-status', message.status]"
                          :title="messageStatusText[message.status]"
                        >
                          <Check v-if="message.status === 'sent'" />
                          <SuccessFilled v-else-if="message.status === 'delivered'" />
                          <CircleCheckFilled v-else-if="message.status === 'read'" />
                        </el-icon>
                      </div>
                    </div>

                    <el-avatar
                      v-if="message.senderId === userId"
                      :size="36"
                      :src="message.senderAvatar"
                      class="sender-avatar"
                    />
                  </div>
                </div>

                <div ref="messageEnd"></div>
              </template>
            </div>

            <!-- 输入区域 -->
            <div class="message-input-container">
              <div class="message-toolbar">
                <el-button-group>
                  <el-button icon="Picture" @click="openImageUpload"></el-button>
                  <el-button icon="Files" @click="openFileUpload"></el-button>
                  <el-button icon="SmileFilled" @click="toggleEmojiPicker"></el-button>
                </el-button-group>
              </div>

              <div class="input-area">
                <el-input
                  v-model="messageText"
                  type="textarea"
                  :rows="3"
                  resize="none"
                  placeholder="输入消息..."
                  @keydown.enter.prevent="sendMessage"
                ></el-input>
              </div>

              <div class="send-button">
                <el-button type="primary" :disabled="!messageText.trim()" @click="sendMessage">
                  发送
                </el-button>
              </div>
            </div>

            <!-- 隐藏的文件上传输入 -->
            <input
              ref="fileInputRef"
              type="file"
              style="display: none"
              @change="handleFileSelected"
            />
            <input
              ref="imageInputRef"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleImageSelected"
            />
          </template>

          <el-empty v-else description="请选择一个好友开始聊天" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ArrowLeft,
  Document,
  Check,
  SuccessFilled,
  CircleCheckFilled,
} from "@element-plus/icons-vue";
import { getFriendList, getChatMessages, sendMessage, markMessagesAsRead } from "@/api/social";
import type { FriendInfo, MessageInfo } from "@/types/social";

const route = useRoute();
const router = useRouter();
const userId = ref(1); // 假设用户ID为1，实际应该从用户状态中获取

// 好友列表
const friendList = ref<FriendInfo[]>([]);
const searchText = ref("");
const filteredFriends = computed(() => {
  if (!searchText.value) return friendList.value;
  const search = searchText.value.toLowerCase();
  return friendList.value.filter(
    (friend) =>
      friend.username.toLowerCase().includes(search) ||
      (friend.nickname && friend.nickname.toLowerCase().includes(search))
  );
});

// 当前选中的好友
const currentFriendId = ref<number | null>(null);
const currentFriend = ref<FriendInfo | null>(null);

// 消息列表
const messages = ref<MessageInfo[]>([]);
const loading = ref(false);
const messageText = ref("");
const messageListRef = ref<HTMLElement | null>(null);
const messageEnd = ref<HTMLElement | null>(null);
const fileInputRef = ref<HTMLInputElement | null>(null);
const imageInputRef = ref<HTMLInputElement | null>(null);

// 消息状态文本
const messageStatusText = {
  sent: "已发送",
  delivered: "已送达",
  read: "已读",
};

// 加载好友列表
const loadFriendList = async () => {
  try {
    const res = await getFriendList();
    friendList.value = res.data || [];

    // 如果路由中有friendId参数，则选中对应好友
    const friendId = route.params.friendId;
    if (friendId) {
      const targetFriend = friendList.value.find((f) => f.id === Number(friendId));
      if (targetFriend) {
        selectFriend(targetFriend);
      }
    }
  } catch (error) {
    console.error("获取好友列表失败:", error);
    ElMessage.error("获取好友列表失败，请稍后重试");
  }
};

// 加载聊天记录
const loadMessages = async () => {
  if (!currentFriendId.value) return;

  loading.value = true;
  try {
    const res = await getChatMessages(currentFriendId.value, {
      pageSize: 50,
      pageNum: 1,
    });
    messages.value = res.data?.messages || [];

    // 标记消息为已读
    const unreadMessages = messages.value
      .filter((m) => m.senderId !== userId.value && m.status !== "read")
      .map((m) => m.id);

    if (unreadMessages.length > 0) {
      await markMessagesAsRead(unreadMessages);
    }

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error("获取聊天记录失败:", error);
    ElMessage.error("获取聊天记录失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 选择好友
const selectFriend = (friend: FriendInfo) => {
  currentFriendId.value = friend.id;
  currentFriend.value = friend;
  router.push(`/social/messages/${friend.id}`);
  loadMessages();
};

// 发送消息
const sendMessage = async () => {
  if (!messageText.value.trim() || !currentFriendId.value) return;

  try {
    await sendMessage({
      receiverId: currentFriendId.value,
      content: messageText.value,
      type: "text",
    });

    // 模拟发送成功，添加消息到列表
    messages.value.push({
      id: Date.now(),
      senderId: userId.value,
      senderName: "我", // 实际应该从用户信息中获取
      senderAvatar: "", // 实际应该从用户信息中获取
      receiverId: currentFriendId.value,
      content: messageText.value,
      type: "text",
      status: "sent",
      createdAt: new Date().toISOString(),
    });

    messageText.value = "";

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送消息失败，请稍后重试");
  }
};

// 返回好友列表
const goBack = () => {
  router.push("/social/friends");
};

// 重新加载消息
const reloadMessages = () => {
  loadMessages();
};

// 打开图片上传
const openImageUpload = () => {
  if (imageInputRef.value) {
    imageInputRef.value.click();
  }
};

// 打开文件上传
const openFileUpload = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
};

// 处理选择的图片
const handleImageSelected = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    // 实际应该调用上传图片API
    ElMessage.success(`已选择图片: ${file.name}`);
    target.value = ""; // 清空选择，以便下次选择同一个文件时触发change事件
  }
};

// 处理选择的文件
const handleFileSelected = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    // 实际应该调用上传文件API
    ElMessage.success(`已选择文件: ${file.name}`);
    target.value = ""; // 清空选择，以便下次选择同一个文件时触发change事件
  }
};

// 切换表情选择器
const toggleEmojiPicker = () => {
  ElMessage.info("表情选择功能待实现");
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageEnd.value) {
    messageEnd.value.scrollIntoView({ behavior: "smooth" });
  }
};

// 获取好友最后一条消息
const getLastMessage = (friend: FriendInfo) => {
  // 实际情况中，这个信息应该从好友对象中获取
  return "暂无消息";
};

// 获取好友最后一条消息时间
const getLastMessageTime = (friend: FriendInfo) => {
  // 实际情况中，这个信息应该从好友对象中获取
  return "";
};

// 判断是否显示日期分隔线
const shouldShowDateDivider = (message: MessageInfo, index: number) => {
  if (index === 0) return true;

  const prevMessage = messages.value[index - 1];
  const prevDate = new Date(prevMessage.createdAt).toLocaleDateString();
  const currentDate = new Date(message.createdAt).toLocaleDateString();

  return prevDate !== currentDate;
};

// 格式化日期分隔线
const formatDateDivider = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toLocaleDateString() === now.toLocaleDateString()) {
    return "今天";
  } else if (date.toLocaleDateString() === yesterday.toLocaleDateString()) {
    return "昨天";
  } else {
    return date.toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
  }
};

// 格式化消息时间
const formatMessageTime = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
};

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return "未知大小";

  const units = ["B", "KB", "MB", "GB", "TB"];
  let size = bytes;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(2)} ${units[unitIndex]}`;
};

// 下载文件
const downloadFile = (message: MessageInfo) => {
  if (!message.fileUrl) {
    ElMessage.error("文件下载链接不存在");
    return;
  }

  window.open(message.fileUrl, "_blank");
};

onMounted(() => {
  loadFriendList();

  // 获取可能存在的friendId参数
  const friendId = route.params.friendId;

  // 如果有friendId参数，重定向并保留参数
  if (friendId) {
    // 用户直接访问了特定聊天的URL，我们可以在当前社交中心内选中该好友
    router.replace("/social/index");
    // 后续可以通过localStorage或其他方式将friendId传递给社交中心页面
    localStorage.setItem("selectedFriendId", friendId as string);
  } else {
    // 直接重定向到社交中心
    router.replace("/social/index");
  }
});

// 监听路由变化
watch(
  () => route.params.friendId,
  (newFriendId) => {
    if (newFriendId && friendList.value.length > 0) {
      const targetFriend = friendList.value.find((f) => f.id === Number(newFriendId));
      if (targetFriend) {
        selectFriend(targetFriend);
      }
    }
  }
);
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: bold;
}

.chat-container {
  display: flex;
  height: 600px;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 10px;
}

// 好友侧边栏
.friends-sidebar {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;

  .search-input {
    padding: 10px;
    border-bottom: 1px solid #e4e7ed;
  }

  .friend-list {
    flex: 1;
    overflow-y: auto;

    .friend-item {
      display: flex;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &.active {
        background-color: #ecf5ff;
      }

      .friend-avatar {
        position: relative;
        margin-right: 10px;

        .status-dot {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          border: 2px solid #fff;

          &.online {
            background-color: #67c23a;
          }

          &.offline {
            background-color: #909399;
          }

          &.busy {
            background-color: #e6a23c;
          }
        }
      }

      .friend-info {
        flex: 1;
        min-width: 0;

        .friend-name {
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 3px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .last-message {
          font-size: 12px;
          color: #909399;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .friend-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        justify-content: space-between;
        min-width: 50px;

        .message-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

// 聊天内容区
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;

  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 15px;

    .loading-container {
      padding: 20px;
    }

    .date-divider {
      text-align: center;
      margin: 10px 0;

      span {
        display: inline-block;
        padding: 2px 10px;
        font-size: 12px;
        background-color: #f2f6fc;
        color: #909399;
        border-radius: 10px;
      }
    }

    .message-item {
      margin-bottom: 15px;
    }

    .message-bubble {
      display: flex;
      align-items: flex-start;

      &.message-sent {
        flex-direction: row-reverse;

        .message-content {
          margin-right: 10px;
        }
      }

      &.message-received {
        flex-direction: row;

        .message-content {
          margin-left: 10px;
        }
      }

      .message-content {
        max-width: 70%;

        .message-text {
          padding: 10px;
          border-radius: 8px;
          margin-bottom: 5px;

          &.sent-text {
            background-color: #95d475;
            color: #fff;
          }

          &.received-text {
            background-color: #fff;
            color: #303133;
          }

          &.image-message {
            padding: 0;
            overflow: hidden;

            .message-image {
              max-width: 200px;
              max-height: 200px;
              border-radius: 8px;
            }
          }

          &.file-message {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .file-name {
              font-weight: bold;
              margin: 0 10px;
              flex: 1;
              word-break: break-all;
            }

            .file-size {
              font-size: 12px;
              color: #909399;
              margin-right: 10px;
            }
          }
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          text-align: right;
          display: flex;
          justify-content: flex-end;
          align-items: center;

          .message-status {
            margin-left: 5px;
            font-size: 14px;

            &.sent {
              color: #909399;
            }

            &.delivered {
              color: #409eff;
            }

            &.read {
              color: #67c23a;
            }
          }
        }
      }
    }
  }

  .message-input-container {
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;

    .message-toolbar {
      padding: 5px 0;
      margin-bottom: 5px;
    }

    .input-area {
      flex: 1;
      margin-bottom: 10px;
    }

    .send-button {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
